/*
 * Copyright (c) 2022 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr/ztest.h>
#include <zephyr/crypto/crypto.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>

#ifdef CONFIG_CRYPTO_MBEDTLS_SHIM
#define CRYPTO_DRV_NAME CONFIG_CRYPTO_MBEDTLS_SHIM_DRV_NAME
#elif DT_HAS_COMPAT_STATUS_OKAY(renesas_smartbond_crypto)
#define CRYPTO_DEV_COMPAT renesas_smartbond_crypto
#elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_hash)
#define CRYPTO_DEV_COMPAT st_stm32_hash
#else
#error "You need to enable one crypto device"
#endif

/* Following test are part of mbedTLS */

uint8_t test1[] = {};
uint8_t test2[] = {0xbd};
uint8_t test3[] = {0x5f, 0xd4};
uint8_t test4[] = {0xb0, 0xbd, 0x69};
uint8_t test5[] = {0xc9, 0x8c, 0x8e, 0x55};
uint8_t test6[] = {0x81, 0xa7, 0x23, 0xd9, 0x66};
uint8_t test7[] = {
	0x83, 0x90, 0xcf, 0x0b, 0xe0, 0x76, 0x61, 0xcc, 0x76, 0x69, 0xaa, 0xc5,
	0x4c, 0xe0, 0x9a, 0x37, 0x73, 0x3a, 0x62, 0x9d, 0x45, 0xf5, 0xd9, 0x83,
	0xef, 0x20, 0x1f, 0x9b, 0x2d, 0x13, 0x80, 0x0e, 0x55, 0x5d, 0x9b, 0x10,
	0x97, 0xfe, 0xc3, 0xb7, 0x83, 0xd7, 0xa5, 0x0d, 0xcb, 0x5e, 0x2b, 0x64,
	0x4b, 0x96, 0xa1, 0xe9, 0x46, 0x3f, 0x17, 0x7c, 0xf3, 0x49, 0x06, 0xbf,
	0x38, 0x8f, 0x36, 0x6d, 0xb5, 0xc2, 0xde, 0xee, 0x04, 0xa3, 0x0e, 0x28,
	0x3f, 0x76, 0x4a, 0x97, 0xc3, 0xb3, 0x77, 0xa0, 0x34, 0xfe, 0xfc, 0x22,
	0xc2, 0x59, 0x21, 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e, 0xfc, 0x77, 0xf7,
	 0x86, 0x59, 0x98, 0x71, 0x4a, 0xad, 0x0b, 0x5e}
};

ZTEST_USER(crypto_hash, test_hash)
{
	int ret;
	struct hash_ctx ctx;

#ifdef CRYPTO_DRV_NAME
	const struct device *dev = device_get_binding(CRYPTO_DRV_NAME);

	if (!dev) {
		zassert(0, "Crypto device is not ready");
	}
#else
	const struct device *dev = DEVICE_DT_GET_ONE(CRYPTO_DEV_COMPAT);

	if (!device_is_ready(dev)) {
		zassert(0, "Crypto device is not ready");
	}
#endif

	ctx.flags = CAP_SYNC_OPS | CAP_SEPARATE_IO_BUFS;

	ret = hash_begin_session(dev, &ctx, CRYPTO_HASH_ALGO_SHA256);
	zassert_true(ret == 0, "Failed to init sha256 session");

#define TEST_HASH(_i) \
	do { \
		uint8_t out_buf[32] = {0};	\
		struct hash_pkt pkt = {			\
			.in_buf = test ## _i,		\
			.in_len = sizeof(test ## _i),	\
			.out_buf = out_buf,		\
		};					\
		ret = hash_compute(&ctx, &pkt);		\
		zassert_true(ret == 0, "Failed to compute hash for test " #_i); \
		ret = memcmp(pkt.out_buf, sha256_results[_i - 1], 32); \
		zassert_true(ret == 0, "Failed to compute hash for test " #_i); \
	} while (0)


	TEST_HASH(1);
	TEST_HASH(2);
	TEST_HASH(3);
	TEST_HASH(4);
	TEST_HASH(5);
	TEST_HASH(6);
	TEST_HASH(7);

	hash_free_session(dev, &ctx);
}

ZTEST_SUITE(crypto_hash, NULL, NULL, NULL, NULL, NULL);
